#!/usr/bin/env python
#coding:utf-8
# 作者：FreddyFrog
# 链接：https://www.jianshu.com/p/1d82045a4fd7
# 來源：简书
# 著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
from PIL import Image
import zbar
import sys,os

def scan_qr(imgPath):
    scanner = zbar.ImageScanner() 
    scanner.parse_config("enable") 
    pil = Image.open(imgPath).convert('L') 
    width, height = pil.size 
    raw = pil.tobytes() 
    image = zbar.Image(width, height, 'Y800', raw) 
    scanner.scan(image) 
    data = '' 
    for symbol in image: 
        # try:
            # data += symbol.data.decode('utf-8').encode('sjis').decode('utf-8') 
        # except: 
        data += symbol.data 
    del(image)
    pil.close() 
    if not data: 
        data += 'Nan' 
        return data
    else:
        return data
          
if __name__ == '__main__':
    if len(sys.argv)==2:
        data = scan_qr(sys.argv[1])
        print(data)
    else:
        n = 0
        while True:
            filename = str(n)+"-qr.png"
            n+=1
            if os.path.exists(filename):
                data = scan_qr(filename)
                print data
            else:
                break
    
